<?php

namespace App\Services;

use App\Jobs\PayGameCbQueue;
use App\Jobs\PaySuccessQueue;
use App\Models\Log\LogPayCb;
use App\Models\Orders;
use App\Services\SwitchPay\SwitchPayBase;
use Illuminate\Http\Request;
use YQ\YqExtend;

class SwitchPayService extends ServiceBase
{
    // 官包支付成功回调
    public function callback(Request $request, $pay_platform, $game_channel_id, $cb_type)
    {
        $game_channel = GameChannelService::getInstance()->get($game_channel_id);
        $game_id      = $game_channel['game_id'];
        $channel      = $game_channel['channel'];
        $payobj       = SwitchPayBase::loadPay($pay_platform, $game_id, $game_channel_id);
        if (!$payobj) {
            return yqerr(6025);
        }

        // 记录请求日志
        $logcb                  = new LogPayCb;
        $logcb->create_time     = time();
        $logcb->game_id         = $game_id;
        $logcb->channel         = $channel;
        $logcb->game_channel_id = $game_channel['id'];
        $logcb->ip              = YqExtend::getIP();
        $logcb->url             = $request->fullUrl();
        $logcb->method          = $request->method();
        $logcb->data            = json_encode($request->post());
        $logcb->input_data      = file_get_contents('php://input');
        $logcb->save();

        // 处理充值回调
        $notify = $payobj->payCb($request, $cb_type);
        if ($notify->errno != 0) {
            return $payobj->payErr();
        }

        $order = $notify->order;
        $trade_no = $notify->tradeNo;

        // 已经是支付成功的 直接返回告诉支付渠道
        if ($order->status !== Orders::PAY_STATUS_CREATE && $order->status !== Orders::PAY_STATUS_RUNING) {
            return $payobj->payOk();
        }

        // 更改订单状态
        $order->pay_platform     = $pay_platform;
        $order->status           = Orders::PAY_STATUS_PAY_OK;
        $order->payok_time       = time();
        $order->channel_trade_no = $notify->channelTradeNo;
        $order->mch_id           = $notify->mchId;
        $order->mch_name         = $notify->mchName;
        $order->cb_type          = $cb_type;
        $payobj->supplementOrderInfo();
        $order->save();

        // 支付成功后处理其他附加任务
        PaySuccessQueue::dispatch($trade_no)->onQueue('default');

        // 通知服务端发货由定时器进行，此处直接返回成功告诉充值渠道
        PayGameCbQueue::dispatch($trade_no, $order->status)->onQueue('high');

        return $payobj->payOk();
    }
}
